package com.heba.greenmulu.hashtag;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.adapter.FmPagerAdapter;
import com.heba.bean.hashtag.ItemHashTagObject;
import com.heba.config.CommonConfig;
import com.heba.fragment.hashtag.HashTagSelectFollowerFragment;
import com.heba.fragment.hashtag.HashTagSelectPhotoFragment;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.DensityUtils;
import com.heba.utils.IndicatorLineUtil;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Objects;

/**
 * HashTag Page
 * Created by jason on 2020/9/28.
 */
public class ItemHashTagPageActivity extends BaseActivity {

    /**
     * topbar
     */
    private ImageView img_back;
    private ImageView img_more;
    private TextView txt_title;

    /**
     * account view
     */
    private ImageView img_avatar;
    private ImageView img_copy_link;
    private ImageView img_message;
    private TextView txt_focus;
    private TextView txt_nickname;
    private TextView txt_desc;
    private int selectIndex = 0;
    private ConstraintLayout bottomLine1;
    /**
     * tablayout
     */
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FmPagerAdapter pagerAdapter;

    /**
     * fragment
     */
    private HashTagSelectPhotoFragment hashTagSelectPhotoFragment;
    private HashTagSelectFollowerFragment hashTagSelectFollowerFragment;
    private ArrayList<Fragment> fragments = new ArrayList<>();

    private ItemHashTagObject hashTagObject;

    /**
     * 获取hashtagID
     */
    private String hashTagID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_person_homgpage);
        findViewById();
        initView();
        initFragments();
        setCustomTabView();
        getHashTagInfoData();
    }

    @Override
    protected void findViewById() {
        img_back = findViewById(R.id.img_diary_write);
        img_more = findViewById(R.id.img_setting);
        txt_title = findViewById(R.id.txt_mine_title);
        img_avatar = findViewById(R.id.img_avatar);
        img_copy_link = findViewById(R.id.img_copy_link);
        img_message = findViewById(R.id.img_message);
        txt_focus = findViewById(R.id.txt_edit_account);
        txt_nickname = findViewById(R.id.txt_nickname);
        txt_desc = findViewById(R.id.txt_desc);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            hashTagID = bundle.getString(CommonConfig.HASHTAG_ID, "");
        }

        img_back.setImageResource(R.drawable.icon_back_white);
        img_more.setImageResource(R.drawable.icon_more_white_point);

        img_back.setOnClickListener(v -> finishActivity());
        bottomLine1 = findViewById(R.id.bottom_line_1);
        img_avatar.setImageResource(R.drawable.icon_head);
        img_more.setVisibility(View.INVISIBLE);
        txt_focus.setVisibility(View.INVISIBLE);
        img_copy_link.setVisibility(View.INVISIBLE);
        img_message.setVisibility(View.INVISIBLE);
        txt_nickname.setVisibility(View.GONE);
//        txt_desc.setVisibility(View.GONE);
    }

    /**
     * initFragments
     */
    private void initFragments() {
        hashTagSelectPhotoFragment = HashTagSelectPhotoFragment.newInstance(hashTagID);
        hashTagSelectFollowerFragment = HashTagSelectFollowerFragment.newInstance(hashTagID);
        fragments.add(hashTagSelectPhotoFragment);
        fragments.add(hashTagSelectFollowerFragment);
    }

    /**
     * 设置自定义tab
     */
    private void setCustomTabView() {
        /**
         * 添加tab
         */
        for (int i = 0; i < 2; i++) {
            tabLayout.addTab(tabLayout.newTab());
        }

        /**
         * 关联viewpager,设置adapter
         */
        tabLayout.setupWithViewPager(viewPager, false);
        pagerAdapter = new FmPagerAdapter(fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);

        /**
         * 设置tab文字,必须在关联viewpager之后设置，否则文字不显示
         */
        Objects.requireNonNull(tabLayout.getTabAt(0)).setCustomView(getTabItemView(R.drawable.image_post_selector));
        Objects.requireNonNull(tabLayout.getTabAt(1)).setCustomView(getTabItemView(R.drawable.image_friends_selector));

        /**
         * 设置指示线长度间隔(单位dp)
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tabLayout, 0, 0);
            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tabLayout.getSelectedTabPosition();
                Resources resources = getResources();
                DisplayMetrics dm = resources.getDisplayMetrics();
                int width3 = dm.widthPixels;
                TranslateAnimation translateAnimation1 = new TranslateAnimation(selectIndex*(width3/2),position*(width3/2),0,0);
                translateAnimation1.setDuration(300);
                translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                translateAnimation1.setFillAfter(true);//不回到起始位置
                bottomLine1.startAnimation(translateAnimation1);


                translateAnimation1.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        selectIndex = tabLayout.getSelectedTabPosition();



                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 获取itemview
     *
     * @param icon
     * @return
     */
    private View getTabItemView(int icon) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab_layout, null);
        ImageView iv_icon = view.findViewById(R.id.iv_icon);
        iv_icon.setImageResource(icon);
        return view;
    }

    /**
     * 更新用戶信息View
     */
    @SuppressLint("ResourceType")
    private void updateHashTagView(ItemHashTagObject object) {
        hashTagSelectPhotoFragment.setPostCount(object.getDiaryCount());
        hashTagSelectFollowerFragment.setFollowerCount(object.getAccountCount());
        txt_title.setText(object.getContent());
        txt_focus.setVisibility(View.VISIBLE);
        txt_focus.setBackground(getDrawable(R.drawable.button_mine_follow_selector1));
        txt_focus.setTextColor(this.getResources().getColorStateList(R.drawable.text_mine_follow_selector1, null));

        if (object.isFollow()) {
            txt_focus.setCompoundDrawables(null, null, null, null);
            txt_focus.setText(getResources().getString(R.string.mine_focus2));
            txt_focus.setSelected(true);
        } else {
            Drawable left = getResources().getDrawable(R.drawable.icon_diary_focus_on, null);
            left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
            txt_focus.setCompoundDrawablePadding(DensityUtils.dip2px(this, 4));
            txt_focus.setCompoundDrawables(left, null, null, null);
            txt_focus.setText(getResources().getString(R.string.mine_focus));
            txt_focus.setSelected(false);
        }

        /**
         * 关注话题
         */
        txt_focus.setOnClickListener(v -> {
            if (!object.isFollow()) {
                loading.Start();
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        loading.End();
                        getHashTagInfoData();
                    }

                    @Override
                    public void Fail(String error) {
                        loading.End();
                    }
                }).followHashTag(this, hashTagID, CommonConfig.HASHTAG_TYPE_ADD);
            } else {
                loading.Start();
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        loading.End();
                        getHashTagInfoData();
                    }

                    @Override
                    public void Fail(String error) {
                        loading.End();
                    }
                }).followHashTag(this, hashTagID, CommonConfig.HASHTAG_TYPE_DELETE);
            }
        });
    }

    /**
     * 获取hashtag info
     */
    private void getHashTagInfoData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("HashtagID", hashTagID);
        client.get(Cfg.BaseUrl + "/Diary/GetHashtagInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            hashTagObject = new Gson().fromJson(jsonObject.toString(), ItemHashTagObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (null != hashTagObject) {
                            updateHashTagView(hashTagObject);
                        }

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

}
